home *** CD-ROM | disk | FTP | other *** search
/ MacFormat España 4 / MacFormat n. 4 (Spain) / MacFormat 4.bin / La ciudad del ShareWare / Desarrollo / macgzip_03b2-src / gzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-01-18  |  41.1 KB  |  1,465 lines

  1. /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * The unzip code was written and put in the public domain by Mark Adler.
  4.  * Portions of the lzw code are derived from the public domain 'compress'
  5.  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  6.  * Ken Turkowski, Dave Mack and Peter Jannesen.
  7.  *
  8.  * See the license_msg below and the file COPYING for the software license.
  9.  * See the file algorithm.doc for the compression algorithms and file formats.
  10.  */
  11.  
  12. /*
  13.  * Modified:1994 by SPDsoft for MacGzip
  14.  * license_msg moved to resource fork...
  15.  */
  16.  
  17. /* Compress files with zip algorithm and 'compress' interface.
  18.  * See usage() and help() functions below for all options.
  19.  * Outputs:
  20.  *        file.gz:   compressed file with same mode, owner, and utimes
  21.  *     or stdout with -c option or if stdin used as input.
  22.  * If the output file name had to be truncated, the original name is kept
  23.  * in the compressed file.
  24.  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
  25.  *
  26.  * Using gz on MSDOS would create too many file name conflicts. For
  27.  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
  28.  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
  29.  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
  30.  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. 
  31.  *
  32.  * For the meaning of all compilation flags, see comments in Makefile.in.
  33.  */
  34.  
  35. #ifdef RCSID
  36. static char rcsid[] = "$Id: gzip.c,v 0.24 1993/06/24 10:52:07 jloup Exp $";
  37. #endif
  38.  
  39. #include <ctype.h>
  40. #include <sys/types.h>
  41. #include <signal.h>
  42. #include <sys/stat.h>
  43. #include <errno.h>
  44.  
  45. #include "tailor.h"
  46. #include "gzip.h"
  47. #include "lzw.h"
  48. #include "revision.h"
  49.  
  50.         /* configuration */
  51.         
  52. #ifdef MACOS
  53.  
  54. #include "MacErrors.h"
  55. #include "ThePrefs.h"
  56. #include "SPDProg.h"
  57.  
  58. local void    init_globals( void );
  59. extern void    FixMacFile( char* name, int ascii, int decompress);
  60. extern int    AsciiMode(char *name, int compress);
  61.  
  62. #endif /* MACOS */
  63.  
  64. #ifdef NO_TIME_H
  65. #  include <sys/time.h>
  66. #else
  67. #  include <time.h>
  68. #endif
  69.  
  70. #ifndef NO_FCNTL_H
  71. #  include <fcntl.h>
  72. #endif
  73.  
  74. #ifdef HAVE_UNISTD_H
  75. #  include <unistd.h>
  76. #endif
  77.  
  78. #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
  79. #  include <stdlib.h>
  80. #else
  81.    extern int errno;
  82. #endif
  83.  
  84. #if defined(DIRENT)
  85. #  include <dirent.h>
  86.    typedef struct dirent dir_type;
  87. #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
  88. #  define DIR_OPT "DIRENT"
  89. #else
  90. #  define NLENGTH(dirent) ((dirent)->d_namlen)
  91. #  ifdef SYSDIR
  92. #    include <sys/dir.h>
  93.      typedef struct direct dir_type;
  94. #    define DIR_OPT "SYSDIR"
  95. #  else
  96. #    ifdef SYSNDIR
  97. #      include <sys/ndir.h>
  98.        typedef struct direct dir_type;
  99. #      define DIR_OPT "SYSNDIR"
  100. #    else
  101. #      ifdef NDIR
  102. #        include <ndir.h>
  103.          typedef struct direct dir_type;
  104. #        define DIR_OPT "NDIR"
  105. #      else
  106. #        define NO_DIR
  107. #        define DIR_OPT "NO_DIR"
  108. #      endif
  109. #    endif
  110. #  endif
  111. #endif
  112.  
  113. #ifndef NO_UTIME
  114. #  ifndef NO_UTIME_H
  115. #    include <utime.h>
  116. #    define TIME_OPT "UTIME"
  117. #  else
  118. #    ifdef HAVE_SYS_UTIME_H
  119. #      include <sys/utime.h>
  120. #      define TIME_OPT "SYS_UTIME"
  121. #    else
  122.        struct utimbuf {
  123.          time_t actime;
  124.          time_t modtime;
  125.        };
  126. #      define TIME_OPT ""
  127. #    endif
  128. #  endif
  129. #else
  130. #  define TIME_OPT "NO_UTIME"
  131. #endif
  132.  
  133. #if !defined(S_ISDIR) && defined(S_IFDIR)
  134. #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  135. #endif
  136. #if !defined(S_ISREG) && defined(S_IFREG)
  137. #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  138. #endif
  139.  
  140. typedef RETSIGTYPE (*sig_type) OF((int));
  141.  
  142. #ifndef    O_BINARY
  143. #  define  O_BINARY  0  /* creation mode for open() */
  144. #endif
  145.  
  146. #ifndef O_CREAT
  147.    /* Pure BSD system? */
  148. #  include <sys/file.h>
  149. #  ifndef O_CREAT
  150. #    define O_CREAT FCREAT
  151. #  endif
  152. #  ifndef O_EXCL
  153. #    define O_EXCL FEXCL
  154. #  endif
  155. #endif
  156.  
  157. #ifndef S_IRUSR
  158. #  define S_IRUSR 0400
  159. #endif
  160. #ifndef S_IWUSR
  161. #  define S_IWUSR 0200
  162. #endif
  163. #define RW_USER (S_IRUSR | S_IWUSR)  /* creation mode for open() */
  164.  
  165. #ifndef MAX_PATH_LEN
  166. #  define MAX_PATH_LEN   1024 /* max pathname length */
  167. #endif
  168.  
  169. #ifndef SEEK_END
  170. #  define SEEK_END 2
  171. #endif
  172.  
  173. #ifdef NO_OFF_T
  174.   typedef long off_t;
  175.   off_t lseek OF((int fd, off_t offset, int whence));
  176. #endif
  177.  
  178. /* Separator for file name parts (see shorten_name()) */
  179. #ifdef NO_MULTIPLE_DOTS
  180. #  define PART_SEP "-"
  181. #else
  182. #  define PART_SEP "."
  183. #endif
  184.  
  185.         /* global buffers */
  186.  
  187. DECLARE(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  188. DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  189. DECLARE(ush, d_buf,  DIST_BUFSIZE);
  190. DECLARE(uch, window, 2L*WSIZE);
  191. #ifndef MAXSEG_64K
  192.     DECLARE(ush, tab_prefix, 1L<<BITS);
  193. #else
  194.     DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
  195.     DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
  196. #endif
  197.  
  198.         /* local variables */
  199.  
  200. int ascii = 0;        /* convert end-of-lines to local OS conventions */
  201. int to_stdout = 0;    /* output to stdout (-c) */
  202. int decompress = 0;   /* decompress (-d) */
  203. int force = 0;        /* don't ask questions, compress links (-f) */
  204. int no_name = -1;     /* don't save or restore the original file name */
  205. int no_time = -1;     /* don't save or restore the original file time */
  206. int recursive = 0;    /* recurse through directories (-r) */
  207. int list = 0;         /* list the file contents (-l) */
  208. int verbose = 0;      /* be verbose (-v) */
  209. int quiet = 0;        /* be very quiet (-q) */
  210. int do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  211. int test = 0;         /* test .gz file integrity */
  212. int foreground;       /* set if program run in foreground */
  213. char *progname="gzip";       /* program name */
  214. int maxbits = BITS;   /* max bits per code for LZW */
  215. int method = DEFLATED;/* compression method */
  216. int level = 6;        /* compression level */
  217. int exit_code = OK;   /* program exit code */
  218. int save_orig_name;   /* set if original name must be saved */
  219. int last_member;      /* set for .zip and .Z files */
  220. int part_nb;          /* number of parts in .gz file */
  221. long time_stamp;      /* original time stamp (modification time) */
  222. long ifile_size;      /* input file size, -1 for devices (debug only) */
  223. char **args = NULL;   /* argv pointer if GZIP env variable defined */
  224. char z_suffix[MAX_SUFFIX+1]; /* default suffix (can be set with --suffix) */
  225. int  z_len;           /* strlen(z_suffix) */
  226.  
  227. long bytes_in;             /* number of input bytes */
  228. long bytes_out;            /* number of output bytes */
  229. long total_in = 0;         /* input bytes for all files */
  230. long total_out = 0;        /* output bytes for all files */
  231. char ifname[MAX_PATH_LEN]; /* input file name */
  232. char ofname[MAX_PATH_LEN]; /* output file name */
  233. int  remove_ofname = 0;       /* remove output file on error */
  234. struct stat istat;         /* status for input file */
  235. int  ifd;                  /* input file descriptor */
  236. int  ofd;                  /* output file descriptor */
  237. unsigned insize;           /* valid bytes in inbuf */
  238. unsigned inptr;            /* index of next byte to be processed in inbuf */
  239. unsigned outcnt;           /* bytes in output buffer */
  240.  
  241.  
  242. /* local functions */
  243.  
  244. local void version      OF((void));
  245. local void treat_file   OF((char *iname));
  246. local int create_outfile OF((void));
  247. local int  do_stat      OF((char *name, struct stat *sbuf));
  248.       char *get_suffix  OF((char *name)); /* used in OpenFile for MacGzip */
  249. local int  get_istat    OF((char *iname, struct stat *sbuf));
  250. local int  make_ofname  OF((void));
  251. local int  same_file    OF((struct stat *stat1, struct stat *stat2));
  252. local int name_too_long OF((char *name, struct stat *statb));
  253. local void shorten_name  OF((char *name));
  254. local int  get_method   OF((int in));
  255. local void do_list      OF((int ifd, int method));
  256. local int  check_ofname OF((void));
  257. local void copy_stat    OF((struct stat *ifstat));
  258. local void do_exit      OF((int exitcode));
  259. /*      int main          OF((int argc, char **argv));*/
  260. int (*work) OF((int infile, int outfile)) = zip; /* function to call */
  261.  
  262. #ifndef NO_DIR
  263. local void treat_dir    OF((char *dir));
  264. #endif
  265. #ifndef NO_UTIME
  266. local void reset_times  OF((char *name, struct stat *statb));
  267. #endif
  268.  
  269. #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
  270.  
  271.  
  272.  
  273. /* ======================================================================== */
  274. local void version()
  275. {
  276.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  277.  
  278.     fprintf(stderr, "Compilation options:\n%s %s ", DIR_OPT, TIME_OPT);
  279. #ifdef STDC_HEADERS
  280.     fprintf(stderr, "STDC_HEADERS ");
  281. #endif
  282. #ifdef HAVE_UNISTD_H
  283.     fprintf(stderr, "HAVE_UNISTD_H ");
  284. #endif
  285. #ifdef NO_MEMORY_H
  286.     fprintf(stderr, "NO_MEMORY_H ");
  287. #endif
  288. #ifdef NO_STRING_H
  289.     fprintf(stderr, "NO_STRING_H ");
  290. #endif
  291. #ifdef NO_SYMLINK
  292.     fprintf(stderr, "NO_SYMLINK ");
  293. #endif
  294. #ifdef NO_MULTIPLE_DOTS
  295.     fprintf(stderr, "NO_MULTIPLE_DOTS ");
  296. #endif
  297. #ifdef NO_CHOWN
  298.     fprintf(stderr, "NO_CHOWN ");
  299. #endif
  300. #ifdef PROTO
  301.     fprintf(stderr, "PROTO ");
  302. #endif
  303. #ifdef ASMV
  304.     fprintf(stderr, "ASMV ");
  305. #endif
  306. #ifdef DEBUG
  307.     fprintf(stderr, "DEBUG ");
  308. #endif
  309. #ifdef DYN_ALLOC
  310.     fprintf(stderr, "DYN_ALLOC ");
  311. #endif
  312. #ifdef MAXSEG_64K
  313.     fprintf(stderr, "MAXSEG_64K");
  314. #endif
  315.     fprintf(stderr, "\n");
  316. }
  317.  
  318. /* ======================================================================== */
  319. int gzip_main (Str255 fName, short Compress)
  320. {
  321.     char filename[64];
  322.  
  323.     init_globals();
  324.  
  325.  
  326.     foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  327.     if (foreground) {
  328.     (void) signal (SIGINT, (sig_type)abort_gzip);
  329.     }
  330. #ifdef SIGTERM
  331.     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
  332.     (void) signal(SIGTERM, (sig_type)abort_gzip);
  333.     }
  334. #endif
  335. #ifdef SIGHUP
  336.     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
  337.     (void) signal(SIGHUP,  (sig_type)abort_gzip);
  338.     }
  339. #endif
  340.     
  341.     level = (int)currPrefs.level;
  342.     if(currPrefs.force) force++;
  343.     
  344.     sprintf((char *)filename,"%#s",fName);
  345.     decompress = !Compress;
  346.     no_name = no_time = 0; /* -N */
  347. /*    no_name = no_time = 1;    -n */
  348.     
  349. /*    -b should be implemented? */            
  350. /*    case 'b':*/
  351. /*        maxbits = atoi(optarg);*/
  352. /*    case 'l':*/
  353. /*        list = decompress = 1;*/
  354. /*    case 'q':*/
  355. /*        quiet = 1; verbose = 0;*/
  356. /*    case 't':*/
  357. /*        test = decompress = 1;*/
  358. /*    case 'v':*/
  359. /*        verbose++; quiet = 0;*/
  360.  
  361. /*    case 'a':*/
  362.     if( Compress )
  363.         if( AsciiMode((char *)fName, true)) ascii = 1;
  364.  
  365.         
  366.  
  367.     /* By default, save name and timestamp on compression but do not
  368.      * restore them on decompression.
  369.      */
  370.     if (no_time < 0) no_time = decompress;
  371.     if (no_name < 0) no_name = decompress;
  372.  
  373.     if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) {
  374.         sprintf(strerr, "incorrect suffix '%s'", filename);
  375.         Calert(strerr);
  376.         do_exit(ERROR);
  377.     }
  378.     if (do_lzw && !decompress) work = lzw;
  379.  
  380.     /* Allocate all global buffers (for DYN_ALLOC option) */
  381.     ALLOC(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  382.     ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  383.     ALLOC(ush, d_buf,  DIST_BUFSIZE);
  384.     ALLOC(uch, window, 2L*WSIZE);
  385. #ifndef MAXSEG_64K
  386.     ALLOC(ush, tab_prefix, 1L<<BITS);
  387. #else
  388.     ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
  389.     ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
  390. #endif
  391.  
  392.     /* And get to work */
  393.  
  394.     treat_file(filename);
  395.     
  396. /*
  397.     if (list && !quiet && file_count > 1) {
  398.     do_list(-1, -1);
  399.     }
  400. */
  401.  
  402.     do_exit(exit_code);
  403.     return exit_code;
  404. }
  405.  
  406.  
  407. /* ========================================================================
  408.  * Compress or decompress the given file
  409.  */
  410. local void treat_file(iname)
  411.     char *iname;
  412. {
  413.     /* Check if the input file is present, set ifname and istat: */
  414.     if (get_istat(iname, &istat) != OK) return;
  415.  
  416.     /* If the input name is that of a directory, recurse or ignore: */
  417.     if (S_ISDIR(istat.st_mode)) {
  418. #ifndef NO_DIR
  419.     if (recursive) {
  420.         struct stat st;
  421.         st = istat;
  422.         treat_dir(iname);
  423.         /* Warning: ifname is now garbage */
  424. #  ifndef NO_UTIME
  425.         reset_times (iname, &st);
  426. #  endif
  427.     } else
  428. #endif
  429.     WARN((strerr,"%s: %s is a directory -- ignored", progname, ifname));
  430.     return;
  431.     }
  432.     if (!S_ISREG(istat.st_mode)) {
  433.     WARN((strerr,
  434.           "%s: %s is not a directory or a regular file - ignored",
  435.           progname, ifname));
  436.     return;
  437.     }
  438.     if (istat.st_nlink > 1 && !to_stdout && !force) {
  439.     WARN((strerr, "%s: %s has %d other link%c -- unchanged",
  440.           progname, ifname,
  441.           (int)istat.st_nlink - 1, istat.st_nlink > 2 ? 's' : ' '));
  442.     return;
  443.     }
  444.  
  445.     ifile_size = istat.st_size;
  446.     time_stamp = no_time && !list ? 0 : istat.st_mtime;
  447.  
  448.     /* Generate output file name. For -r and (-t or -l), skip files
  449.      * without a valid gzip suffix (check done in make_ofname).
  450.      */
  451.     if (to_stdout && !list && !test) {
  452.     strcpy(ofname, "stdout");
  453.  
  454.     } else if (make_ofname() != OK) {
  455.     return;
  456.     }
  457.  
  458.     /* Open the input file and determine compression method. The mode
  459.      * parameter is ignored but required by some systems (VMS) and forbidden
  460.      * on other systems (MacOS).
  461.      */
  462.      
  463.      /* MacGzip 0.2.2 */
  464.     ifd = OPEN(ifname, ascii && !decompress ? O_RDONLY | O_TEXT : O_RDONLY | O_BINARY,
  465.            RW_USER);
  466.            
  467.     if (ifd == -1) {
  468.     PError(ifname);
  469.     exit_code = ERROR;
  470.     return;
  471.     }
  472.     clear_bufs(); /* clear input and output buffers */
  473.     part_nb = 0;
  474.  
  475.     if (decompress) {
  476.     method = get_method(ifd); /* updates ofname if original given */
  477.     if (method < 0) {
  478.         close(ifd);
  479.         return;               /* error message already emitted */
  480.     }
  481.     }
  482.     if (list) {
  483.         do_list(ifd, method);
  484.         close(ifd);
  485.         return;
  486.     }
  487.  
  488.     /* If compressing to a file, check if ofname is not ambiguous
  489.      * because the operating system truncates names. Otherwise, generate
  490.      * a new ofname and save the original name in the compressed file.
  491.      */
  492.     if (to_stdout) {
  493.     ofd = fileno(stdout);
  494.     /* keep remove_ofname as zero */
  495.     } else {
  496.     if (create_outfile() != OK)
  497.     {
  498.         exit_code = -1; /* in a mac, we don't want
  499.                          * so little thing to make us exit
  500.                          */
  501.         return;
  502.     }
  503.     
  504.     if (!decompress && save_orig_name && !verbose && !quiet) {
  505.         
  506.         sprintf(strerr, "%s: %s compressed to %s",
  507.             progname, ifname, ofname);
  508.         
  509.         Calert(strerr);
  510.     }
  511.     }
  512.     /* Keep the name even if not truncated except with --no-name: */
  513.     if (!save_orig_name) save_orig_name = !no_name;
  514.  
  515.     if (verbose) {
  516.     fprintf(stderr, "%s:\t%s", ifname, (int)strlen(ifname) >= 15 ? 
  517.         "" : ((int)strlen(ifname) >= 7 ? "\t" : "\t\t"));
  518.     }
  519.  
  520.     /* Actually do the compression/decompression. Loop over zipped members.
  521.      */
  522.     for (;;) {
  523.     
  524. #ifdef _SPD_PROG_
  525.          sprintf(SPDpstr, "%s (%s): %s -> %s",
  526.          progname,
  527.          ascii ? "ascii" : "bin",
  528.          ifname, ofname);
  529.          InitAnimatedCursors(kCalCursorRes);
  530.          InitMovableModal((unsigned long int) istat.st_size);
  531. #endif
  532.     
  533.     if ( (*work)(ifd, ofd) != OK) {
  534.         method = -1; /* force cleanup */
  535.         break;
  536.     }
  537.     
  538.     if (!decompress || last_member || inptr == insize) break;
  539.     /* end of file */
  540.  
  541.     method = get_method(ifd);
  542.     if (method < 0) break;    /* error message already emitted */
  543.     bytes_out = 0;            /* required for length check */
  544.     }
  545.  
  546.     close(ifd);
  547.     if (!to_stdout && close(ofd)) {
  548.     write_error();
  549.     }
  550.     if (method == -1) {
  551.     if (!to_stdout) unlink (ofname);
  552.     return;
  553.     }
  554.     /* Display statistics */
  555.     if(verbose) {
  556.     if (test) {
  557.         fprintf(stderr, " OK");
  558.     } else if (decompress) {
  559.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
  560.     } else {
  561.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
  562.     }
  563.     if (!test && !to_stdout) {
  564.         fprintf(stderr, " -- replaced with %s", ofname);
  565.     }
  566.     fprintf(stderr, "\n");
  567.     }
  568.     /* Copy modes, times, ownership, and remove the input file */
  569.     if (!to_stdout) {
  570.     copy_stat(&istat);
  571.     }
  572. }
  573.  
  574. /* ========================================================================
  575.  * Create the output file. Return OK or ERROR.
  576.  * Try several times if necessary to avoid truncating the z_suffix. For
  577.  * example, do not create a compressed file of name "1234567890123."
  578.  * Sets save_orig_name to true if the file name has been truncated.
  579.  * IN assertions: the input file has already been open (ifd is set) and
  580.  *   ofname has already been updated if there was an original name.
  581.  * OUT assertions: ifd and ofd are closed in case of error.
  582.  */
  583. local int create_outfile()
  584. {
  585.     struct stat    ostat; /* stat for ofname */
  586.     int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
  587.  
  588. #ifdef MACOS
  589.     /* if compress, ascii has been set in OpenFile */
  590.     if (decompress)
  591.     {
  592.         ascii = AsciiMode(ofname, 0);
  593.     }
  594. #endif /* MACOS */
  595.  
  596.     if (ascii && decompress) {
  597. #ifndef MACOS
  598.     flags &= ~O_BINARY; /* force ascii text mode */
  599. #else
  600.     flags = O_WRONLY | O_CREAT | O_EXCL | O_TEXT; /* MacGzip */
  601. #endif /*MACOS*/
  602.     }
  603.     for (;;) {
  604.     /* Make sure that ofname is not an existing file */
  605.     if (check_ofname() != OK) {
  606.         close(ifd);
  607.         return ERROR;
  608.     }
  609.     /* Create the output file */
  610.     remove_ofname = 1;
  611.     ofd = OPEN(ofname, flags, RW_USER);
  612.     if (ofd == -1) {
  613.         PError(ofname);
  614.         close(ifd);
  615.         exit_code = ERROR;
  616.         return ERROR;
  617.     }
  618.     
  619. #ifdef MACOS
  620.     FixMacFile(ofname, ascii, decompress);
  621. #endif /* MACOS */
  622.  
  623.     /* Check for name truncation on new file (1234567890123.gz) */
  624. #ifdef NO_FSTAT
  625.     if (stat(ofname, &ostat) != 0) {
  626. #else
  627.     if (fstat(ofd, &ostat) != 0) {
  628. #endif
  629.         PError(ofname);
  630.         close(ifd); close(ofd);
  631.         unlink(ofname);
  632.         exit_code = ERROR;
  633.         return ERROR;
  634.     }
  635.     if (!name_too_long(ofname, &ostat)) return OK;
  636.  
  637.     if (decompress) {
  638.         /* name might be too long if an original name was saved */
  639.         WARN((strerr, "%s: %s: warning, name truncated",
  640.           progname, ofname));
  641.         return OK;
  642.     }
  643.     close(ofd);
  644.     unlink(ofname);
  645. #ifdef NO_MULTIPLE_DOTS
  646.     /* Should never happen, see check_ofname() */
  647.     sprintf(strerr, "%s: name too long", ofname);
  648.     Calert(strerr);
  649.     do_exit(ERROR);
  650. #endif
  651.     shorten_name(ofname);
  652.     }
  653. }
  654.  
  655. /* ========================================================================
  656.  * Use lstat if available, except for -c or -f. Use stat otherwise.
  657.  * This allows links when not removing the original file.
  658.  */
  659. local int do_stat(name, sbuf)
  660.     char *name;
  661.     struct stat *sbuf;
  662. {
  663.     errno = 0;
  664. #if (defined(S_IFLNK) || defined (S_ISLNK)) && !defined(NO_SYMLINK)
  665.     if (!to_stdout && !force) {
  666.     return lstat(name, sbuf);
  667.     }
  668. #endif
  669.     return stat(name, sbuf);
  670. }
  671.  
  672. /* ========================================================================
  673.  * Return a pointer to the 'z' suffix of a file name, or NULL. For all
  674.  * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
  675.  * accepted suffixes, in addition to the value of the --suffix option.
  676.  * ".tgz" is a useful convention for tar.z files on systems limited
  677.  * to 3 characters extensions. On such systems, ".?z" and ".??z" are
  678.  * also accepted suffixes. For Unix, we do not want to accept any
  679.  * .??z suffix as indicating a compressed file; some people use .xyz
  680.  * to denote volume data.
  681.  *   On systems allowing multiple versions of the same file (such as VMS),
  682.  * this function removes any version suffix in the given name.
  683.  */
  684. char *get_suffix(name)
  685.     char *name;
  686. {
  687.     int nlen, slen;
  688.     char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
  689.     static char *known_suffixes[] =
  690.        {z_suffix, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
  691. #ifdef MAX_EXT_CHARS
  692.           "z",
  693. #endif
  694.           NULL};
  695.     char **suf = known_suffixes;
  696.  
  697.    if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
  698.  
  699. #ifdef SUFFIX_SEP
  700.     /* strip a version number from the file name */
  701.     {
  702.     char *v = strrchr(name, SUFFIX_SEP);
  703.      if (v != NULL) *v = '\0';
  704.     }
  705. #endif
  706.     nlen = strlen(name);
  707.     if (nlen <= MAX_SUFFIX+2) {
  708.         strcpy(suffix, name);
  709.     } else {
  710.         strcpy(suffix, name+nlen-MAX_SUFFIX-2);
  711.     }
  712.     strlwr(suffix);
  713.     slen = strlen(suffix);
  714.     do {
  715.        int s = strlen(*suf);
  716.        if (slen > s && suffix[slen-s-1] != PATH_SEP
  717.            && strequ(suffix + slen - s, *suf)) {
  718.            return name+nlen-s;
  719.        }
  720.     } while (*++suf != NULL);
  721.  
  722.     return NULL;
  723. }
  724.  
  725.  
  726. /* ========================================================================
  727.  * Set ifname to the input file name (with a suffix appended if necessary)
  728.  * and istat to its stats. For decompression, if no file exists with the
  729.  * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
  730.  * For MSDOS, we try only z_suffix and z.
  731.  * Return OK or ERROR.
  732.  */
  733. local int get_istat(iname, sbuf)
  734.     char *iname;
  735.     struct stat *sbuf;
  736. {
  737.     int ilen;  /* strlen(ifname) */
  738.     static char *suffixes[] = {z_suffix, ".gz", ".z", "-z", ".Z", NULL};
  739.     char **suf = suffixes;
  740.     char *s;
  741. #ifdef NO_MULTIPLE_DOTS
  742.     char *dot; /* pointer to ifname extension, or NULL */
  743. #endif
  744.  
  745.     strcpy(ifname, iname);
  746.  
  747.     /* If input file exists, return OK. */
  748.     if (do_stat(ifname, sbuf) == 0) return OK;
  749.  
  750.     if (!decompress || errno != ENOENT) {
  751.     PError(ifname);
  752.     exit_code = ERROR;
  753.     return ERROR;
  754.     }
  755.     /* file.ext doesn't exist, try adding a suffix (after removing any
  756.      * version number for VMS).
  757.      */
  758.     s = get_suffix(ifname);
  759.     if (s != NULL) {
  760.     PError(ifname); /* ifname already has z suffix and does not exist */
  761.     exit_code = ERROR;
  762.     return ERROR;
  763.     }
  764. #ifdef NO_MULTIPLE_DOTS
  765.     dot = strrchr(ifname, '.');
  766.     if (dot == NULL) {
  767.         strcat(ifname, ".");
  768.         dot = strrchr(ifname, '.');
  769.     }
  770. #endif
  771.     ilen = strlen(ifname);
  772.     if (strequ(z_suffix, ".gz")) suf++;
  773.  
  774.     /* Search for all suffixes */
  775.     do {
  776.         s = *suf;
  777. #ifdef NO_MULTIPLE_DOTS
  778.         if (*s == '.') s++;
  779. #endif
  780. #ifdef MAX_EXT_CHARS
  781.         strcpy(ifname, iname);
  782.         /* Needed if the suffixes are not sorted by increasing length */
  783.  
  784.         if (*dot == '\0') strcpy(dot, ".");
  785.         dot[MAX_EXT_CHARS+1-strlen(s)] = '\0';
  786. #endif
  787.         strcat(ifname, s);
  788.         if (do_stat(ifname, sbuf) == 0) return OK;
  789.     ifname[ilen] = '\0';
  790.     } while (*++suf != NULL);
  791.  
  792.     /* No suffix found, complain using z_suffix: */
  793. #ifdef MAX_EXT_CHARS
  794.     strcpy(ifname, iname);
  795.     if (*dot == '\0') strcpy(dot, ".");
  796.     dot[MAX_EXT_CHARS+1-z_len] = '\0';
  797. #endif
  798.     strcat(ifname, z_suffix);
  799.     PError(ifname);
  800.     exit_code = ERROR;
  801.     return ERROR;
  802. }
  803.  
  804. /* ========================================================================
  805.  * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
  806.  * Sets save_orig_name to true if the file name has been truncated.
  807.  */
  808. local int make_ofname()
  809. {
  810.     char *suff;            /* ofname z suffix */
  811.  
  812.     strcpy(ofname, ifname);
  813.     /* strip a version number if any and get the gzip suffix if present: */
  814.     suff = get_suffix(ofname);
  815.  
  816.     if (decompress) {
  817.     if (suff == NULL) {
  818.         /* Whith -t or -l, try all files (even without .gz suffix)
  819.          * except with -r (behave as with just -dr).
  820.              */
  821.             if (!recursive && (list || test)) return OK;
  822.  
  823.         /* Avoid annoying messages with -r */
  824.         if (verbose || (!recursive && !quiet)) {
  825.         WARN((strerr,"%s: %s: unknown suffix -- ignored",
  826.               progname, ifname));
  827.         }
  828.         return WARNING;
  829.     }
  830.     /* Make a special case for .tgz and .taz: */
  831.     strlwr(suff);
  832.     if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
  833.         strcpy(suff, ".tar");
  834.     } else {
  835.         *suff = '\0'; /* strip the z suffix */
  836.     }
  837.         /* ofname might be changed later if infile contains an original name */
  838.  
  839.     } else if (suff != NULL) {
  840.     /* Avoid annoying messages with -r (see treat_dir()) */
  841.     if (verbose || (!recursive && !quiet)) {
  842.         sprintf(strerr, "%s already has %s suffix -- unchanged", ifname, suff);
  843.         Calert(strerr);
  844.     }
  845.     if (exit_code == OK) exit_code = WARNING;
  846.     return WARNING;
  847.     } else {
  848.         save_orig_name = 0;
  849.  
  850. #ifdef NO_MULTIPLE_DOTS
  851.     suff = strrchr(ofname, '.');
  852.     if (suff == NULL) {
  853.             strcat(ofname, ".");
  854. #  ifdef MAX_EXT_CHARS
  855.         if (strequ(z_suffix, "z")) {
  856.         strcat(ofname, "gz"); /* enough room */
  857.         return OK;
  858.         }
  859.         /* On the Atari and some versions of MSDOS, name_too_long()
  860.          * does not work correctly because of a bug in stat(). So we
  861.          * must truncate here.
  862.          */
  863.         } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
  864.             suff[MAX_SUFFIX+1-z_len] = '\0';
  865.             save_orig_name = 1;
  866. #  endif
  867.         }
  868. #endif /* NO_MULTIPLE_DOTS */
  869.     strcat(ofname, z_suffix);
  870.  
  871.     } /* decompress ? */
  872.     return OK;
  873. }
  874.  
  875.  
  876. /* ========================================================================
  877.  * Check the magic number of the input file and update ofname if an
  878.  * original name was given and to_stdout is not set.
  879.  * Return the compression method, -1 for error, -2 for warning.
  880.  * Set inptr to the offset of the next byte to be processed.
  881.  * Updates time_stamp if there is one and --no-time is not used.
  882.  * This function may be called repeatedly for an input file consisting
  883.  * of several contiguous gzip'ed members.
  884.  * IN assertions: there is at least one remaining compressed member.
  885.  *   If the member is a zip file, it must be the only one.
  886.  */
  887. local int get_method(in)
  888.     int in;        /* input file descriptor */
  889. {
  890.     uch flags;     /* compression flags */
  891.     char magic[2]; /* magic header */
  892.     ulg stamp;     /* time stamp */
  893.  
  894.     /* If --force and --stdout, zcat == cat, so do not complain about
  895.      * premature end of file: use try_byte instead of get_byte.
  896.      */
  897.     if (force && to_stdout) {
  898.     magic[0] = (char)try_byte();
  899.     magic[1] = (char)try_byte();
  900.     /* If try_byte returned EOF, magic[1] == 0xff */
  901.     } else {
  902.     magic[0] = (char)get_byte();
  903.     magic[1] = (char)get_byte();
  904.     }
  905.     method = -1;                 /* unknown yet */
  906.     part_nb++;                   /* number of parts in gzip file */
  907.     header_bytes = 0;
  908.     last_member = RECORD_IO;
  909.     /* assume multiple members in gzip file except for record oriented I/O */
  910.  
  911.     if (memcmp(magic, GZIP_MAGIC, 2) == 0
  912.         || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
  913.  
  914.     method = (int)get_byte();
  915.     if (method != DEFLATED) {
  916.         sprintf(strerr,
  917.             "%s: unknown method %d -- get newer version of gzip", ifname, method);
  918.         Calert(strerr);
  919.         exit_code = ERROR;
  920.         return -1;
  921.     }
  922.     work = unzip;
  923.     flags  = (uch)get_byte();
  924.     if ((flags & ENCRYPTED) != 0) {
  925.         sprintf(strerr,
  926.             "%s is encrypted -- get newer version of gzip", ifname);
  927.         Calert(strerr);
  928.         exit_code = ERROR;
  929.         return -1;
  930.     }
  931.     if ((flags & CONTINUATION) != 0) {
  932.         sprintf(strerr,
  933.        "%s is a a multi-part gzip file -- get newer version of gzip", ifname);
  934.        Calert(strerr);
  935.         exit_code = ERROR;
  936.         if (force <= 1) return -1;
  937.     }
  938.     if ((flags & RESERVED) != 0) {
  939.         sprintf(strerr,
  940.             "%s has flags 0x%x -- get newer version of gzip", ifname, flags);
  941.         Calert(strerr);
  942.         exit_code = ERROR;
  943.         if (force <= 1) return -1;
  944.     }
  945.     stamp  = (ulg)get_byte();
  946.     stamp |= ((ulg)get_byte()) << 8;
  947.     stamp |= ((ulg)get_byte()) << 16;
  948.     stamp |= ((ulg)get_byte()) << 24;
  949.     if (stamp != 0 && !no_time) time_stamp = stamp;
  950.  
  951.     (void)get_byte();  /* Ignore extra flags for the moment */
  952.     (void)get_byte();  /* Ignore OS type for the moment */
  953.  
  954.     if ((flags & CONTINUATION) != 0) {
  955.         unsigned part = (unsigned)get_byte();
  956.         part |= ((unsigned)get_byte())<<8;
  957.         if (verbose) {
  958.         fprintf(stderr,"%s: %s: part number %u\n",
  959.             progname, ifname, part);
  960.         }
  961.     }
  962.     if ((flags & EXTRA_FIELD) != 0) {
  963.         unsigned len = (unsigned)get_byte();
  964.         len |= ((unsigned)get_byte())<<8;
  965.         if (verbose) {
  966.         fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
  967.             progname, ifname, len);
  968.         }
  969.         while (len--) (void)get_byte();
  970.     }
  971.  
  972.     /* Get original file name if it was truncated */
  973.     if ((flags & ORIG_NAME) != 0) {
  974.         if (no_name || (to_stdout && !list) || part_nb > 1) {
  975.         /* Discard the old name */
  976.         char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
  977.         do {c=get_byte();} while (c != 0);
  978.         } else {
  979.         /* Copy the base name. Keep a directory prefix intact. */
  980.                 char *p = basename(ofname);
  981.                 char *base = p;
  982.         for (;;) {
  983.             *p = (char)get_char();
  984.             if (*p++ == '\0') break;
  985.             if (p >= ofname+sizeof(ofname)) {
  986.             error("corrupted input -- file name too large");
  987.             }
  988.         }
  989.                 /* If necessary, adapt the name to local OS conventions: */
  990.                 if (!list) {
  991.                    MAKE_LEGAL_NAME(base);
  992.            if (base) list=0; /* avoid warning about unused variable */
  993.                 }
  994.         } /* no_name || to_stdout */
  995.     } /* ORIG_NAME */
  996.  
  997.     /* Discard file comment if any */
  998.     if ((flags & COMMENT) != 0) {
  999.         while (get_char() != 0) /* null */ ;
  1000.     }
  1001.     if (part_nb == 1) {
  1002.         header_bytes = inptr + 2*sizeof(long); /* include crc and size */
  1003.     }
  1004.  
  1005.     } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
  1006.         && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
  1007.     /* To simplify the code, we support a zip file when alone only.
  1008.          * We are thus guaranteed that the entire local header fits in inbuf.
  1009.          */
  1010.         inptr = 0;
  1011.     work = unzip;
  1012.     if (check_zipfile(in) != OK) return -1;
  1013.     /* check_zipfile may get ofname from the local header */
  1014.     last_member = 1;
  1015.  
  1016.     } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
  1017.     work = unpack;
  1018.     method = PACKED;
  1019.  
  1020.     } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
  1021.     work = unlzw;
  1022.     method = COMPRESSED;
  1023.     last_member = 1;
  1024.  
  1025.     } else if (memcmp(magic, LZH_MAGIC, 2) == 0) {
  1026.     work = unlzh;
  1027.     method = LZHED;
  1028.     last_member = 1;
  1029.  
  1030.     } else if (force && to_stdout && !list) { /* pass input unchanged */
  1031.     method = STORED;
  1032.     work = copy;
  1033.         inptr = 0;
  1034.     last_member = 1;
  1035.     }
  1036.     if (method >= 0) return method;
  1037.     if (part_nb == 1) {
  1038.     sprintf(strerr, "%s: not in gzip format", ifname);
  1039.     Calert(strerr);
  1040.     exit_code = ERROR;
  1041.     return -1;
  1042.     } else {
  1043.     WARN((strerr, "%s: %s: decompression OK, trailing garbage ignored",
  1044.           progname, ifname));
  1045.     return -2;
  1046.     }
  1047. }
  1048.  
  1049. /* ========================================================================
  1050.  * Display the characteristics of the compressed file.
  1051.  * If the given method is < 0, display the accumulated totals.
  1052.  * IN assertions: time_stamp, header_bytes and ifile_size are initialized.
  1053.  */
  1054. local void do_list(ifd, method)
  1055.     int ifd;     /* input file descriptor */
  1056.     int method;  /* compression method */
  1057. {
  1058.     ulg crc;  /* original crc */
  1059.     static int first_time = 1;
  1060.     static char* methods[MAX_METHODS] = {
  1061.         "store",  /* 0 */
  1062.         "compr",  /* 1 */
  1063.         "pack ",  /* 2 */
  1064.         "lzh  ",  /* 3 */
  1065.         "", "", "", "", /* 4 to 7 reserved */
  1066.         "defla"}; /* 8 */
  1067.     char *date;
  1068.  
  1069.     if (first_time && method >= 0) {
  1070.     first_time = 0;
  1071.     if (verbose)  {
  1072.         printf("method  crc     date  time  ");
  1073.     }
  1074.     if (!quiet) {
  1075.         printf("compressed  uncompr. ratio uncompressed_name\n");
  1076.     }
  1077.     } else if (method < 0) {
  1078.     if (total_in <= 0 || total_out <= 0) return;
  1079.     if (verbose) {
  1080.         printf("                            %9lu %9lu ",
  1081.            total_in, total_out);
  1082.     } else if (!quiet) {
  1083.         printf("%9ld %9ld ", total_in, total_out);
  1084.     }
  1085.     display_ratio(total_out-(total_in-header_bytes), total_out, stdout);
  1086.     /* header_bytes is not meaningful but used to ensure the same
  1087.      * ratio if there is a single file.
  1088.      */
  1089.     printf(" (totals)\n");
  1090.     return;
  1091.     }
  1092.     crc = (ulg)~0; /* unknown */
  1093.     bytes_out = -1L;
  1094.     bytes_in = ifile_size;
  1095.  
  1096. #if RECORD_IO == 0
  1097.     if (method == DEFLATED && !last_member) {
  1098.         /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files.
  1099.          * If the lseek fails, we could use read() to get to the end, but
  1100.          * --list is used to get quick results.
  1101.          * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if
  1102.          * you are not concerned about speed.
  1103.          */
  1104.         bytes_in = (long)lseek(ifd, (off_t)(-8), SEEK_END);
  1105.         if (bytes_in != -1L) {
  1106.             uch buf[8];
  1107.             bytes_in += 8L;
  1108.             if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) {
  1109.                 read_error();
  1110.             }
  1111.             crc       = LG(buf);
  1112.         bytes_out = LG(buf+4);
  1113.     }
  1114.     }
  1115. #endif /* RECORD_IO */
  1116.     date = ctime((time_t*)&time_stamp) + 4; /* skip the day of the week */
  1117.     date[12] = '\0';               /* suppress the 1/100sec and the year */
  1118.     if (verbose) {
  1119.         printf("%5s %08lx %11s ", methods[method], crc, date);
  1120.     }
  1121.     printf("%9ld %9ld ", bytes_in, bytes_out);
  1122.     if (bytes_in  == -1L) {
  1123.     total_in = -1L;
  1124.     bytes_in = bytes_out = header_bytes = 0;
  1125.     } else if (total_in >= 0) {
  1126.     total_in  += bytes_in;
  1127.     }
  1128.     if (bytes_out == -1L) {
  1129.     total_out = -1L;
  1130.     bytes_in = bytes_out = header_bytes = 0;
  1131.     } else if (total_out >= 0) {
  1132.     total_out += bytes_out;
  1133.     }
  1134.     display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout);
  1135.     printf(" %s\n", ofname);
  1136. }
  1137.  
  1138. /* ========================================================================
  1139.  * Return true if the two stat structures correspond to the same file.
  1140.  */
  1141. local int same_file(stat1, stat2)
  1142.     struct stat *stat1;
  1143.     struct stat *stat2;
  1144. {
  1145.     return stat1->st_ino   == stat2->st_ino
  1146.     && stat1->st_dev   == stat2->st_dev
  1147. #ifdef NO_ST_INO
  1148.         /* Can't rely on st_ino and st_dev, use other fields: */
  1149.     && stat1->st_mode  == stat2->st_mode
  1150.     && stat1->st_uid   == stat2->st_uid
  1151.     && stat1->st_gid   == stat2->st_gid
  1152.     && stat1->st_size  == stat2->st_size
  1153.     && stat1->st_atime == stat2->st_atime
  1154.     && stat1->st_mtime == stat2->st_mtime
  1155.     && stat1->st_ctime == stat2->st_ctime
  1156. #endif
  1157.         ;
  1158. }
  1159.  
  1160. /* ========================================================================
  1161.  * Return true if a file name is ambiguous because the operating system
  1162.  * truncates file names.
  1163.  */
  1164. local int name_too_long(name, statb)
  1165.     char *name;           /* file name to check */
  1166.     struct stat *statb;   /* stat buf for this file name */
  1167. {
  1168.     int s = strlen(name);
  1169.     char c = name[s-1];
  1170.     struct stat    tstat; /* stat for truncated name */
  1171.     int res;
  1172.  
  1173.     tstat = *statb;      /* Just in case OS does not fill all fields */
  1174.     name[s-1] = '\0';
  1175.     res = stat(name, &tstat) == 0 && same_file(statb, &tstat);
  1176.     name[s-1] = c;
  1177.     Trace((stderr, " too_long(%s) => %d\n", name, res));
  1178.     return res;
  1179. }
  1180.  
  1181. /* ========================================================================
  1182.  * Shorten the given name by one character, or replace a .tar extension
  1183.  * with .tgz. Truncate the last part of the name which is longer than
  1184.  * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name
  1185.  * has only parts shorter than MIN_PART truncate the longest part.
  1186.  * For decompression, just remove the last character of the name.
  1187.  *
  1188.  * IN assertion: for compression, the suffix of the given name is z_suffix.
  1189.  */
  1190. local void shorten_name(name)
  1191.     char *name;
  1192. {
  1193.     int len;                 /* length of name without z_suffix */
  1194.     char *trunc = NULL;      /* character to be truncated */
  1195.     int plen;                /* current part length */
  1196.     int min_part = MIN_PART; /* current minimum part length */
  1197.     char *p;
  1198.  
  1199.     len = strlen(name);
  1200.     if (decompress) {
  1201.     if (len <= 1) error("name too short");
  1202.     name[len-1] = '\0';
  1203.     return;
  1204.     }
  1205.     p = get_suffix(name);
  1206.     if (p == NULL) error("can't recover suffix\n");
  1207.     *p = '\0';
  1208.     save_orig_name = 1;
  1209.  
  1210.     /* compress 1234567890.tar to 1234567890.tgz */
  1211.     if (len > 4 && strequ(p-4, ".tar")) {
  1212.     strcpy(p-4, ".tgz");
  1213.     return;
  1214.     }
  1215.     /* Try keeping short extensions intact:
  1216.      * 1234.678.012.gz -> 123.678.012.gz
  1217.      */
  1218.     do {
  1219.     p = strrchr(name, PATH_SEP);
  1220.     p = p ? p+1 : name;
  1221.     while (*p) {
  1222.         plen = strcspn(p, PART_SEP);
  1223.         p += plen;
  1224.         if (plen > min_part) trunc = p-1;
  1225.         if (*p) p++;
  1226.     }
  1227.     } while (trunc == NULL && --min_part != 0);
  1228.  
  1229.     if (trunc != NULL) {
  1230.     do {
  1231.         trunc[0] = trunc[1];
  1232.     } while (*trunc++);
  1233.     trunc--;
  1234.     } else {
  1235.     trunc = strrchr(name, PART_SEP[0]);
  1236.     if (trunc == NULL) error("internal error in shorten_name");
  1237.     if (trunc[1] == '\0') trunc--; /* force truncation */
  1238.     }
  1239.     strcpy(trunc, z_suffix);
  1240. }
  1241.  
  1242. /* ========================================================================
  1243.  * If compressing to a file, check if ofname is not ambiguous
  1244.  * because the operating system truncates names. Otherwise, generate
  1245.  * a new ofname and save the original name in the compressed file.
  1246.  * If the compressed file already exists, ask for confirmation.
  1247.  *    The check for name truncation is made dynamically, because different
  1248.  * file systems on the same OS might use different truncation rules (on SVR4
  1249.  * s5 truncates to 14 chars and ufs does not truncate).
  1250.  *    This function returns -1 if the file must be skipped, and
  1251.  * updates save_orig_name if necessary.
  1252.  * IN assertions: save_orig_name is already set if ofname has been
  1253.  * already truncated because of NO_MULTIPLE_DOTS. The input file has
  1254.  * already been open and istat is set.
  1255.  */
  1256. local int check_ofname()
  1257. {
  1258.     struct stat    ostat; /* stat for ofname */
  1259.  
  1260. #ifdef ENAMETOOLONG
  1261.     /* Check for strictly conforming Posix systems (which return ENAMETOOLONG
  1262.      * instead of silently truncating filenames).
  1263.      */
  1264.     errno = 0;
  1265.     while (stat(ofname, &ostat) != 0) {
  1266.         if (errno != ENAMETOOLONG) return 0; /* ofname does not exist */
  1267.     shorten_name(ofname);
  1268.     }
  1269. #else
  1270. #ifdef MACOS
  1271.     while (strlen(ofname) > 31) shorten_name(ofname);
  1272. #endif
  1273.     if (stat(ofname, &ostat) != 0) return 0;
  1274. #endif
  1275.     /* Check for name truncation on existing file. Do this even on systems
  1276.      * defining ENAMETOOLONG, because on most systems the strict Posix
  1277.      * behavior is disabled by default (silent name truncation allowed).
  1278.      */
  1279.     if (!decompress && name_too_long(ofname, &ostat)) {
  1280.     shorten_name(ofname);
  1281.     if (stat(ofname, &ostat) != 0) return 0;
  1282.     }
  1283.  
  1284.     /* Check that the input and output files are different (could be
  1285.      * the same by name truncation or links).
  1286.      */
  1287.     if (same_file(&istat, &ostat)) {
  1288.     if (strequ(ifname, ofname)) {
  1289.         sprintf(strerr, "%s: cannot %scompress onto itself",ifname, decompress ? "de" : "");
  1290.         Calert(strerr);
  1291.     } else {
  1292.         sprintf(strerr, "%s and %s are the same file", ifname, ofname);
  1293.         Calert(strerr);
  1294.     }
  1295.     exit_code = ERROR;
  1296.     return ERROR;
  1297.     }
  1298.     /* Ask permission to overwrite the existing file */
  1299.  
  1300.     if (!force) {
  1301.     sprintf(strerr, " %s already exists; do you wish to overwrite ?", ofname);
  1302.  
  1303.     if (Cask(strerr)==cancel) {
  1304.         if (exit_code == OK) exit_code = WARNING;
  1305.         return ERROR;
  1306.     }
  1307.     }
  1308.  
  1309.     (void) chmod(ofname, 0777);
  1310.     if (unlink(ofname)) {
  1311.     PError(ofname);
  1312.     exit_code = ERROR;
  1313.     return ERROR;
  1314.     }
  1315.     return OK;
  1316. }
  1317.  
  1318.  
  1319. #ifndef NO_UTIME
  1320. /* ========================================================================
  1321.  * Set the access and modification times from the given stat buffer.
  1322.  */
  1323. local void reset_times (name, statb)
  1324.     char *name;
  1325.     struct stat *statb;
  1326. {
  1327.     struct utimbuf    timep;
  1328.  
  1329.     /* Copy the time stamp */
  1330.     timep.actime  = statb->st_atime;
  1331.     timep.modtime = statb->st_mtime;
  1332.  
  1333.     /* Some systems (at least OS/2) do not support utime on directories */
  1334.     if (utime(name, &timep) && !S_ISDIR(statb->st_mode)) {
  1335.     if (!quiet) PError(ofname);
  1336.     }
  1337. }
  1338. #endif
  1339.  
  1340.  
  1341. /* ========================================================================
  1342.  * Copy modes, times, ownership from input file to output file.
  1343.  * IN assertion: to_stdout is false.
  1344.  */
  1345. local void copy_stat(ifstat)
  1346.     struct stat *ifstat;
  1347. {
  1348. #ifndef NO_UTIME
  1349.     if (decompress && time_stamp != 0 && ifstat->st_mtime != time_stamp) {
  1350.     ifstat->st_mtime = time_stamp;
  1351.     if (verbose > 1) {
  1352.         fprintf(stderr, "%s: time stamp restored\n", ofname);
  1353.     }
  1354.     }
  1355.     reset_times(ofname, ifstat);
  1356. #endif
  1357.     /* Copy the protection modes */
  1358.     if (chmod(ofname, ifstat->st_mode & 07777)) {
  1359.     if (!quiet) PError(ofname);
  1360.     }
  1361. #ifndef NO_CHOWN
  1362.     chown(ofname, ifstat->st_uid, ifstat->st_gid);  /* Copy ownership */
  1363. #endif
  1364.     remove_ofname = 0;
  1365.     /* It's now safe to remove the input file: */
  1366.     
  1367. /* MacGzip 0.2.2 */
  1368.  
  1369.     if(!currPrefs.KeepOriginals)
  1370.     {
  1371.         (void) chmod(ifname, 0777);
  1372.         if (unlink(ifname)) {
  1373.         if (!quiet) PError(ifname);
  1374.         }
  1375.     }
  1376. }
  1377.  
  1378. #ifndef NO_DIR
  1379.  
  1380. /* ========================================================================
  1381.  * Recurse through the given directory. This code is taken from ncompress.
  1382.  */
  1383. local void treat_dir(dir)
  1384.     char *dir;
  1385. {
  1386.  
  1387. }
  1388. #endif /* ? NO_DIR */
  1389.  
  1390. /* ========================================================================
  1391.  * Free all dynamically allocated variables and exit with the given code.
  1392.  */
  1393. local void do_exit(int exitcode)
  1394. {
  1395.     static int in_exit = 0;
  1396.  
  1397.     if (in_exit) exit(exitcode);
  1398.     in_exit = 1;
  1399.  
  1400.     FREE(inbuf);
  1401.     FREE(outbuf);
  1402.     FREE(d_buf);
  1403.     FREE(window);
  1404. #ifndef MAXSEG_64K
  1405.     FREE(tab_prefix);
  1406. #else
  1407.     FREE(tab_prefix0);
  1408.     FREE(tab_prefix1);
  1409. #endif
  1410. #ifdef MACOS
  1411.      ReleaseAnimatedCursors(kCalCursorRes);
  1412.      ReleaseMovableModal();
  1413. #endif
  1414.     if ((exitcode==0)||(exitcode==-1)) /* -1 for can't create outname */
  1415.     {
  1416.         in_exit = 0;
  1417.         return;
  1418.     }
  1419.     else
  1420.         exit(exitcode);
  1421. }
  1422.  
  1423. /* ========================================================================
  1424.  * Signal and error handler.
  1425.  */
  1426. RETSIGTYPE abort_gzip()
  1427. {
  1428.    if (remove_ofname) {
  1429.        close(ofd);
  1430.        unlink (ofname);
  1431.    }
  1432.    do_exit(ERROR);
  1433. }
  1434.  
  1435. /*________________________________________________________________________
  1436.  *
  1437.  *         INIT THE OPTIONS
  1438.  */
  1439.  
  1440. local void init_globals( void )
  1441. {    
  1442.     ascii = 0;        /* convert end-of-lines to local OS conventions */
  1443.     to_stdout = 0;    /* output to stdout (-c) */
  1444.     decompress = 0;   /* decompress (-d) */
  1445.     force = 0;        /* don't ask questions, compress links (-f) */
  1446.     no_name = -1;     /* don't save or restore the original file name */
  1447.     no_time = -1;     /* don't save or restore the original file time */
  1448.     recursive = 0;    /* recurse through directories (-r) */
  1449.     list = 0;         /* list the file contents (-l) */
  1450.     verbose = 0;      /* be verbose (-v) */
  1451.     quiet = 0;        /* be very quiet (-q) */
  1452.     do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  1453.     test = 0;         /* test .gz file integrity */
  1454.     maxbits = BITS;   /* max bits per code for LZW */
  1455.     method = DEFLATED;/* compression method */
  1456.     level = 6;        /* compression level */
  1457.     exit_code = OK;   /* program exit code */
  1458.  
  1459.     total_in = 0;         /* input bytes for all files */
  1460.     total_out = 0;        /* output bytes for all files */
  1461.     remove_ofname = 0;       /* remove output file on error */
  1462.  
  1463.  
  1464.     work = zip;
  1465. }